package com.itheima.service.impl;

import com.itheima.dao.AddressDao;
import com.itheima.entity.Address;
import com.itheima.entity.PageBean;
import com.itheima.service.AddressService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    private AddressDao addressDao;

    /**
     * 通过aid查询一个地址
     * @param aid
     */
    @Override
    public Address findByAid(int aid) {
        return null;
    }

    /**
     * 通过uid查询某个用户1页的地址
     * @param current 第几页
     * @param size 每页大小
     * @param uid 用户id
     */
    @Override
    public PageBean<Address> findAddress(int current, int size, Map<String, Object> condition, int uid) {
        //计算起始行数，从0开始
        int begin = (current - 1) * size;
        //查询1页的数据
        List<Address> data = addressDao.findByUid(uid, condition, begin, size);
        //查询总记录数
        int count = addressDao.findCount(uid, condition);
        return new PageBean<>(data, count, current, size);
    }

    /**
     * 保存地址
     * @param address
     */
    @Override
    public void save(Address address) {
        //将默认地址设置为0
        address.setIsdefault("0");
        //调用dao保存地址
        addressDao.save(address);
    }

    /**
     * 更新地址信息
     * @param address
     */
    @Override
    public void update(Address address) {
        addressDao.update(address);
    }

    /**
     * 删除
     * @param aid
     */
    @Override
    public void delete(Integer aid) {
        addressDao.delete(aid);
    }

    /**
     * 设置默认地址，必须开启事务
     * @param uid 用户id
     * @param aid 地址id
     */
    @Override
    @Transactional
    public void changeDefaultAddress(Integer uid, Integer aid) {
        //更新当前用户所有的默认地址为0
        addressDao.updateAddressIsNotDefault(uid);
        //更新一条地址为1
        addressDao.updateAddressIsDefault(aid);
    }
}
